<?php

namespace app\module\middleware;

use app\util\Token;
use Swoole\Http\Request;
use Swoole\Http\Response;

/**
 * Class AuthCheck
 * 中间件默认写法 暂无自定义
 * @package app\module\middleware
 */
class AuthCheck
{
    /**
     * 执行方法
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    public function run(Request $request, Response $response): Response
    {
        $tokenStr = $request->header['token'] ?? 'a.a.a';
        if (empty($tokenStr)) return $this->writeResponse($response);
        if (is_string($this->getInfo($tokenStr))) return $this->writeResponse($response);
        return $response;
    }

    private function writeResponse(Response $response): Response
    {
        $response->write(json_encode(['code' => -1, 'msg' => '登录信息失效']));
        $response->end();
        return $response;
    }

    public function getInfo($tokenStr): array
    {
        $token = new Token();
        return $token->decode($tokenStr);
    }
}